package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.ServiceProperty;
import com.huaweicloud.sdk.iotda.v5.model.ShowProductRequest;
import com.huaweicloud.sdk.iotda.v5.model.ShowProductResponse;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.DevicePropertyDto;
import com.zzyl.nursing.dto.MemberDeviceDataDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-26
 */
@Service
@Slf4j
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
                                                             );

    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private IoTDAClient iotClient;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询家人健康数据
     *
     * @return 设备属性状态列表
     */
    @Override
    public PropertyStatusInfoVoList queryDevicePropertyStatus(DevicePropertyDto devicePropertyDto) {
        // 1.根据设备名称和产品key查询设备信息
        Device device = deviceMapper.selectOne(
                new LambdaQueryWrapper<Device>().eq(Device::getDeviceName, devicePropertyDto.getDeviceName())
                                                .eq(Device::getProductKey, devicePropertyDto.getProductKey()));

        if (ObjectUtil.isEmpty(device)) {
            throw new BaseException("设备不存在");
        }

        // 2.获取设备的数据
        // 2.1 获取设备数据
        String deviceDataStr = (String) redisTemplate.opsForHash()
                                                     .get(CacheConstants.IOT_DEVICE_LAST_DATA, device.getIotId());
        List<DeviceData> deviceDataList = JSONUtil.toList(deviceDataStr, DeviceData.class);
        if (CollUtil.isEmpty(deviceDataList)) {
            throw new BaseException("当前设备暂无数据，请检查设备状况或联系家人");
        }

        // 2.2 获取设备属性
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(device.getProductKey());
        ShowProductResponse response;
        try {
            response = iotClient.showProduct(request);
        }
        catch (Exception e) {
            throw new BaseException("查询产品详情失败！");
        }
        List<ServiceProperty> properties = response.getServiceCapabilities().get(0).getProperties();
        if (CollUtil.isEmpty(properties)) {
            return (PropertyStatusInfoVoList) Collections.emptyList();
        }

        // 3.组装并返回结果
        List<PropertyStatusInfo> propertyStatusInfoList = new ArrayList<>();
        properties.forEach(property -> {
            PropertyStatusInfo propertyStatusInfo = new PropertyStatusInfo();
            propertyStatusInfo.setDataType(property.getDataType());
            propertyStatusInfo.setIdentifier(property.getPropertyName());
            propertyStatusInfo.setName(property.getDescription());
            propertyStatusInfo.setUnit(property.getUnit());

            deviceDataList.forEach(deviceData -> {
                if (propertyStatusInfo.getIdentifier().equals(deviceData.getFunctionId())) {
                    // 将字符串转为Double
                    double value = Double.parseDouble(deviceData.getDataValue());
                    // 使用String.format格式化保留一位小数
                    String formattedValue = String.format("%.1f", value);
                    propertyStatusInfo.setValue(formattedValue);

                    // 将上报时间转为时间戳
                    propertyStatusInfo.setTime(
                            String.valueOf(deviceData.getAlarmTime().toInstant(ZoneOffset.of("+8")).toEpochMilli()));
                }
            });

            propertyStatusInfoList.add(propertyStatusInfo);
        });

        log.info("设备数据：{}", propertyStatusInfoList);

        PropertyStatusInfoVoList propertyStatusInfoVoList = new PropertyStatusInfoVoList();
        PropertyStatusInfoVo propertyStatusInfoVo = new PropertyStatusInfoVo();
        propertyStatusInfoVo.setPropertyStatusInfo(propertyStatusInfoList);
        propertyStatusInfoVoList.setList(propertyStatusInfoVo);
        return propertyStatusInfoVoList;
    }

    /**
     * 按天查询指标数据
     *
     * @return 指标数据
     */
    @Override
    public List<Map<String, Double>> queryDeviceDataListByDay(MemberDeviceDataDto memberDeviceDataDto) {
        // 1.将开始时间戳和结束时间戳转为LocalDateTime
        LocalDateTime startTime = LocalDateTimeUtil.of(memberDeviceDataDto.getStartTime());
        LocalDateTime endTime = LocalDateTimeUtil.of(memberDeviceDataDto.getEndTime());

        // 2.查询设备数据并返回
        return deviceDataMapper.queryDeviceDataListByDay(
                memberDeviceDataDto.getIotId(),
                memberDeviceDataDto.getFunctionId(),
                startTime,
                endTime
                                                        );
    }

    /**
     * 按周查询指标数据
     *
     * @return 指标数据
     */
    @Override
    public List<Map<String, Double>> queryDeviceDataListByWeek(MemberDeviceDataDto memberDeviceDataDto) {
        // 1.将开始时间戳和结束时间戳转为LocalDateTime
        LocalDateTime startTime = LocalDateTimeUtil.of(memberDeviceDataDto.getStartTime());
        LocalDateTime endTime = LocalDateTimeUtil.of(memberDeviceDataDto.getEndTime());

        // 2.查询设备数据并返回
        return deviceDataMapper.queryDeviceDataListByWeek(
                memberDeviceDataDto.getIotId(),
                memberDeviceDataDto.getFunctionId(),
                startTime,
                endTime
                                                         );
    }

    /**
     * 小程序端登录
     *
     * @param dto 登录信息
     * @return 登录信息
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {

        //获取openid  微信接口获取
        String openid = wechatService.getOpenid(dto.getCode());

        //根据openid查询用户信息
        FamilyMember familyMember = getOne(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openid));

        //如果用户为空，构建用户，赋值一个openid
        if (ObjectUtil.isEmpty(familyMember)) {
            familyMember = FamilyMember
                    .builder()
                    .openId(openid)
                    .build();
        }

        //获取用户的手机号  微信接口获取
        String phone = wechatService.getPhone(dto.getPhoneCode());

        //保存或更新用户
        insertOrUpdateFamilyMember(familyMember, phone);

        //生成token返回
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", familyMember.getId());
        claims.put("userName", familyMember.getName());

        String token = tokenService.createToken(claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName(familyMember.getName());
        loginVo.setToken(token);

        return loginVo;
    }

    /**
     * 保存或更新用户
     *
     * @param familyMember 用户信息
     * @param phone        手机号
     */
    private void insertOrUpdateFamilyMember(FamilyMember familyMember, String phone) {

        //判断手机号与数据库的手机号是否一致
        if (ObjectUtil.notEqual(familyMember.getPhone(), phone)) {
            familyMember.setPhone(phone);
        }
        //判断是否存在id，如果存在id，则更新，不存在则保存
        if (ObjectUtil.isNotEmpty(familyMember.getId())) {
            updateById(familyMember);
            return;
        }
        //获取用户的昵称
        int index = (int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size());
        String nickName = DEFAULT_NICKNAME_PREFIX.get(index) + StringUtils.substring(phone, 7, 11);
        familyMember.setName(nickName);
        //保存
        save(familyMember);

    }
}
